<template>
  <div>
    <el-form :model="basicForm" ref="basicForm" :rules="rules" label-width="90px" class="demo-ruleForm"
             :disabled="power">
      <div class="form">
        <span style="font-size: 16px">委托信息</span>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="业务类型" prop="ywlx">
              <el-input type="text" v-model="basicForm.ywlx" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <!-- <el-form-item label="委托书编号" prop="ywbh"> -->
            <el-form-item label="业务编号" prop="ywbh">
              <el-input type="text" v-model="basicForm.ywbh" disabled>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="对接人" prop="djr">
              <el-input type="text" v-model="basicForm.djr"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="委托合同类型" prop="wtslx">
              <el-input type="text" v-model="basicForm.wtslx" disabled>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div class="form">
        <span style="font-size: 16px">业务信息</span>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="评估目的" prop="pgmd">
              <el-input type="text" v-model="basicForm.pgmd" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="评估基准日" prop="pgjzr">
              <el-date-picker v-model="basicForm.pgjzr" type="date" placeholder="选择日期" @change="pgdate()">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="佐证" prop="zz">
              <el-select v-model="basicForm.zz" clearable>
                <el-option value="无佐证" label="无佐证"></el-option>
                <el-option value="有佐证" label="有佐证"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div class="lastform">
        <span style="font-size: 16px">人员信息 </span>
        <el-dropdown placement="right" @command="handleCommand">
          <span class="el-dropdown-link"> 添加人员信息 </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="申请人">申请人</el-dropdown-item>
            <el-dropdown-item command="受益人">受益人</el-dropdown-item>
            <el-dropdown-item command="实际所有人">实际所有人</el-dropdown-item>
            <el-dropdown-item v-if="wtflx != '司法机构'" command="被保险人">被保险人</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <div v-for="(item, index) in formData" :key="index" ref="formData">
          <el-form :model="item" :ref="item" :rules="rules" label-width="90px" class="demo-ruleForm" :disabled="power">
            <el-row :gutter="24">
              <el-col :span="6">
                <el-form-item :label="item.rylx" prop="name">
                  <el-input type="text" v-model="item.name"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="联系电话" prop="phone">
                  <el-input type="number" v-model="item.phone"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="证件号" prop="zjh">
                  <el-input type="text" v-model="item.zjh"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="地址" prop="address">
                  <div style="display: flex">
                    <el-input type="text" v-model="item.address"></el-input>
                    <el-button v-if="index > 1" type="danger" size="small" @click="del(index)"
                               style="padding: 6px 10px">删除
                    </el-button>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <div class="form">
        <span style="font-size: 16px">车辆信息 </span>
        <el-dropdown placement="right" @command="carCommand">
          <span class="el-dropdown-link"> 上传行车证，图文识别，自动填充 </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="行驶证">上传行驶证</el-dropdown-item>
            <el-dropdown-item command="登记证">上传登记证</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>

        <span class="el-dropdown-link" style="margin-left: 60px;cursor: pointer"
              @click="editClxxLabel">修改车辆信息表单</span>

        <el-row :gutter="24" style="flex-wrap: wrap; display: flex;">
          <el-col :span="6" v-for="cl in clxx" :key="cl.id">
            <el-form-item v-if="cl.type == '数值'" :label="cl.labelName" :prop='cl.dbName'>
              <el-input type="number" v-model="cl.data"></el-input>
            </el-form-item>

            <el-form-item v-if="cl.type == '文本'" :label="cl.labelName" :prop='cl.dbName'>
              <el-input type="text" v-model="cl.data"></el-input>
            </el-form-item>

            <el-form-item v-if="cl.type == '时间日期'" :label="cl.labelName" :prop='cl.dbName'>
              <el-date-picker v-model="cl.data" type="date" placeholder="选择日期" style="width: 100%">
              </el-date-picker>
            </el-form-item>

            <el-form-item v-if="cl.type == '下拉选择框'" :label='cl.labelName' :prop='cl.dbName'>
              <el-select v-model="cl.data">
                <el-option v-for="l in cl.values" :key="l" :label='l' :value='l'></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item v-if="!power">
          <div>
            <div style="display:flex">
              <div v-if="sczj == '行驶证'">
                <div slot="tip" class="el-upload__tip">正页</div>
                <el-upload :action="actionurl" list-type="picture-card" :on-preview="handlePictureCardPreview"
                           :on-remove="handleRemove1" :on-change="handleChange1" :on-progress="handleProgress"
                           :before-upload="beforeAvatarUpload1" :file-list="fileList1"
                           :class="{ hide_box1: upload_btn1 }">
                  <i class="el-icon-plus"></i>
                </el-upload>
              </div>
              <div v-if="sczj == '行驶证'">
                <div slot="tip" class="el-upload__tip" style="margin-left:20px">副页</div>
                <el-upload :action="actionurl" list-type="picture-card" :on-preview="handlePictureCardPreview"
                           :on-success="handleSuccess2" :on-remove="handleRemove2" :on-change="handleChange2"
                           :on-progress="handleProgress" :before-upload="beforeAvatarUpload2" :file-list="fileList2"
                           style="margin-left:20px" :class="{ hide_box2: upload_btn2 }">
                  <i class="el-icon-plus"></i>
                </el-upload>
              </div>
              <div v-if="sczj == '登记证'">
                <div slot="tip" class="el-upload__tip">登记证</div>
                <el-upload :action="actionur2" list-type="picture-card" :on-preview="handlePictureCardPreview"
                           :on-success="handleSuccess3" :on-remove="handleRemove3" :on-change="handleChange3"
                           :on-progress="handleProgress" :before-upload="beforeAvatarUpload3" :file-list="fileList3"
                           :class="{ hide_box3: upload_btn3 }">
                  <i class="el-icon-plus"></i>
                </el-upload>
              </div>
            </div>
            <div v-if="sczj == '登记证'" slot="tip" class="el-upload__tip">请上传完整信息页（包括第1页和第2页）</div>
            <!--            <div slot="tip" class="el-upload__tip">支持文件类型：图片(.jpg .jpeg .png)</div>-->
          </div>
          <el-dialog :visible.sync="dialogVisible" width="50%">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>

        </el-form-item>
      </div>
    </el-form>

    <div class="but">
      <el-button v-if="!power" type="primary" @click="submitForm()">保存
      </el-button>
      <el-button v-if="power" type="primary" @click="next()">下一页</el-button>
    </div>

    <!--  修改车辆信息表单  -->
    <el-drawer title="车辆信息表单" size="60%" :visible.sync="isShowEditClxxLabel" style="text-align: center"
               @close="closeDrawer">
      <el-form :inline="true" size="small" style="margin: 20px">
        <div v-for="(c1,index) in clxxLabel" :key="index">
          <el-row>
            <el-col :span="22">
              <div>
                <el-form-item label="表单名">
                  <el-input v-model="c1.labelName" style="width: 150px"></el-input>
                </el-form-item>
                <el-form-item label="字段名">
                  <el-input v-model="c1.dbName" :readonly="c1.defaults" style="width: 100px" @input="zdmInput(index)"></el-input>
                </el-form-item>
                <el-form-item label="模板对应变量">
                  <el-input v-model="c1.wordName" :readonly="true" style="width: 100px"></el-input>
                </el-form-item>
                <el-form-item label="类型">
                  <el-select v-model="c1.type" placeholder="请选择" style="width: 130px">
                    <el-option
                      v-for="item in clxxLabelType"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="优先级">
                  <el-input-number v-model="c1.priority" controls-position="right" :min="1" :max="100"
                                   style="width: 100px"></el-input-number>
                </el-form-item>
                <!--    下拉列表选项      -->
                <el-form-item v-if="c1.type == '下拉选择框'" label="下拉列表选项">
                  <el-tag :key="tag" v-for="tag in c1.values" closable :disable-transitions="false"
                          size="small" @close="handleClose(tag,index)">{{ tag }}
                  </el-tag>

                  <el-input v-if="elTagInputVisible[index]" class="input-new-tag" v-model="elTagInput[index]"
                            :ref="elTagInputRefs[index]"
                            size="small" @keyup.enter.native="handleInputConfirm(index)"
                            @blur="handleInputConfirm(index)"
                  ></el-input>

                  <el-button v-else class="button-new-tag" size="small" @click="showEgInput(index)">添加选项
                  </el-button>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="2">
              <el-popconfirm confirm-button-text='好的' cancel-button-text='取消' icon="el-icon-info" icon-color="red"
                             title="确定删除此字段吗？"
                             @confirm="deleteClxxLabel(index)">
                <i class="el-icon-delete" slot="reference" style="color:#F56C6C;cursor: pointer;margin-top: 20px"></i>
              </el-popconfirm>
            </el-col>
          </el-row>
          <el-divider></el-divider>
        </div>

        <el-row>
          <el-col :span="22">
            <el-button @click="closeDrawer">取消</el-button>
            <el-button type="primary" @click="saveClxxLabel">保存</el-button>
          </el-col>
          <el-col :span="2">
            <i class="el-icon-plus" style="color:#409EFF;cursor: pointer;font-size: 20px;margin-top: 10px"
               @click="addClxxLabel"></i>
          </el-col>
        </el-row>


      </el-form>
    </el-drawer>
  </div>
</template>
<script>
import {findByName} from '@/api/systemManage/dataDictionary';
import {saveJcxx, selectById, getAccessToken} from '@/api/evaluation/newBusiness';
import {getLabel, updateLabel, deleteLabel} from '@/api/evaluation/clxx';
import axios from 'axios'
// import { getCyyByPgmd } from "@/api/evaluation/word";
export default {
  name: 'basicInformation',
  props: {
    ywid: {
      type: Number
    },
    ywzt: {
      type: String
    }
  },
  data() {
    return {
      power: false,
      sczj: '',
      wtflx: '',
      optionsCar: [],
      ywlx: '',
      basicForm: {djrq: ''},
      formData: [],
      clxx: [],
      clxxLabel: [],
      clxxLabelType: [
        {
          value: '数值',
          label: '数值'
        }, {
          value: '文本',
          label: '文本'
        }, {
          value: '下拉选择框',
          label: '下拉选择框'
        }, {
          value: '时间日期',
          label: '时间日期'
        }
      ],
      isShowEditClxxLabel: false,
      isShowElTag: false,
      elTagInputVisible: [],
      elTagInput: [],
      elTagInputRefs: [],

      rylx: '',
      actionurl: '/api/xszsb/xszUpload',
      actionur2: '/api/xszsb/djzUpload',
      dialogVisible: false,
      dialogImageUrl: '',
      upload_btn1: false,
      upload_btn2: false,
      upload_btn3: false,
      fileList1: [],
      fileList2: [],
      fileList3: [],
      accessToken: '',
      rules: {
        ywlx: [
          {required: true, message: '请选择业务类型', trigger: 'change,blur'}
        ],
        pgmd: [
          {required: true, message: '请选择评估目的', trigger: 'change,blur'}
        ],
        pgjzr: [
          {
            required: true,
            message: '请选择评估基准日',
            trigger: 'change,blur'
          }
        ],
        zz: [
          {
            required: true,
            message: '请选择是否有佐证',
            trigger: 'change,blur'
          }
        ],
        name: [
          {required: true, message: '请输入人员姓名', trigger: 'change,blur'}
        ]
      }
    }
  },
  methods: {
    ywtype() {
      findByName('input=' + '车辆类型').then((res) => {
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].dictName == '车辆类型')
            this.optionsCar.push({
              label: res.data[i].dictValue,
              value: res.data[i].dictValue
            })
        }
      })
    },
    handleCommand(command) {
      this.rylx = command
      this.formData.push({
        rylx: command,
        name: '',
        phone: '',
        zjh: '',
        address: ''
      })
    },
    carCommand(command) {
      this.sczj = command
    },
    del(index) {
      if (index > 1) {
        this.formData.splice(index, 1)
      }
    },
    pgdate() {
      if (this.basicForm.djrq && this.basicForm.pgjzr) {
        var num = (this.basicForm.pgjzr - this.basicForm.djrq) / 86400000 / 30
        if (num < 0) {
          this.basicForm.ysynx = '0天'
        } else if (num >= 0) {
          this.basicForm.ysynx = num.toFixed(0) + '个月'
        } else {
          this.basicForm.ysynx = parseInt(num * 30) + '天'
        }
      }
    },
    djdate() {
      if (this.basicForm.djrq && this.basicForm.pgjzr) {
        let da = Date.parse(new Date(this.basicForm.pgjzr).toString())
        let num = da - this.basicForm.djrq
        if (num <= 0) {
          this.basicForm.ysynx = '0天'
        } else {
          num = num / 86400000
          if (num > 30) {
            this.basicForm.ysynx = Math.round(num / 30) + '个月'
          } else {
            this.basicForm.ysynx = Math.round(num) + '天'
          }
        }
      }

    },

    submitForm() {
      this.$refs.basicForm.validate((valid) => {
        if (valid) {
          this.basicForm.ywid = this.ywid
          var obj = {jcxx: {}, ryxx: []}
          obj.jcxx = this.basicForm
          obj.ryxx = this.formData
          obj.clxx = this.clxx
          let loadingInstance = this.$loading()
          saveJcxx(obj).then((res) => {
            loadingInstance.close()
            this.$message.success('保存成功！')
            this.$emit('nextTab')
          })
        } else {
          return
        }
      })
    },
    next() {
      this.$emit('nextTab')
    },
    typel(value) {
      this.ywlx = value
    },
    gettest() {
      if (localStorage.getItem('role') == '高级评估师' || localStorage.getItem('role') == '企业管理员') {
        this.power = true
      }
      selectById('id=' + this.ywid).then((res) => {

        this.basicForm = res.data.jcxx
        this.ywlx = this.basicForm.ywlx
        this.formData = res.data.ryxx
        if (!this.basicForm.wtslx) {
          this.basicForm.wtslx = res.data.wtht.wthtlx
        }
        if (!this.basicForm.pgmd) {
          this.basicForm.pgmd = res.data.wtht.pgmd
        }
        this.wtflx = res.data.wtht.wtflx
        if (!this.basicForm.pgjzr) {
          this.basicForm.pgjzr = res.data.wtht.pgjzr
        }
        if (this.basicForm.djrq && this.basicForm.pgjzr) {
          var num = (this.basicForm.pgjzr - this.basicForm.djrq) / 86400000 / 30
          if (num >= 1) {
            this.basicForm.ysynx = num.toFixed(0) + '个月'
          } else {
            this.basicForm.ysynx = parseInt(num * 30) + '天'
          }
        }
        if (this.formData.length == 0) {
          this.formData.push(
            {
              rylx: '委托人',
              name: '',
              phone: '',
              zjh: '',
              address: ''
            },
            {
              rylx: '所有人',
              name: '',
              phone: '',
              zjh: '',
              address: ''
            }
          )
        }
        if (!this.formData[0].name) {
          if (this.wtflx == '个人') {
            this.formData[0].name = res.data.wtht.wtf
            this.formData[0].phone = res.data.wtht.wtfLxfs
            this.formData[0].zjh = res.data.wtht.wtfXydm
            this.formData[0].address = res.data.wtht.wtfDz

          } else if (this.wtflx == '企业机构') {
            this.formData[0].name = res.data.wtht.wtfFrSqdb
            this.formData[0].phone = res.data.wtht.wtfLxfs
            this.formData[0].zjh = res.data.wtht.wtfXydm
            this.formData[0].address = res.data.wtht.wtfDz
          } else if (this.wtflx == '司法机构') {
            this.formData[0].name = res.data.wtht.jdsqr
            this.formData[0].phone = res.data.wtht.jdsqrPhone
          }

        }

      })
    },
    getLabel() {
      getLabel(this.ywid).then(
        res => {
          this.clxx = res.data
          this.clxxLabel = res.data
        }
      )
    },
    handleRemove1(file) {
      this.upload_btn1 = false
    },
    handleRemove2(file) {
      this.upload_btn2 = false
    },
    handleRemove3(file) {
      this.upload_btn3 = false
    },

    beforeAvatarUpload1(file) {
      this.checkAndHandleCompression(file).then(fileOptions => {
        let {uploadSrc, uploadFile} = fileOptions;
        // 压缩完成使用 uploadSrc, uploadFile
        const params = new FormData();
        params.append('file', uploadFile)
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        setTimeout(() => {
          axios.post("/api/xszsb/xszUpload", params)
            .then((res) => {
              if (res) {

                let params = new URLSearchParams()
                params.append('url', res.data.data)
                axios.post("https://aip.baidubce.com/rest/2.0/ocr/v1/vehicle_license?access_token=" + this.accessToken, params)
                  .then((res) => {
                    if (res.data.words_result.车辆识别代号) {
                      this.basicForm.sbdm = res.data.words_result.车辆识别代号.words
                    }
                    if (res.data.words_result.车辆类型) {
                      this.basicForm.lx = res.data.words_result.车辆类型.words
                    }
                    if (res.data.words_result.使用性质) {
                      this.basicForm.syxz = res.data.words_result.使用性质.words
                    }
                    if (res.data.words_result.品牌型号) {
                      var ppxh = res.data.words_result.品牌型号.words
                      var i
                      for (i = 0; i < ppxh.length; i++) {
                        if (ppxh[i] == '牌') {
                          break;
                        }
                      }
                      this.basicForm.pp = ppxh.slice(0, i + 1)
                      this.basicForm.ggxh = ppxh.slice(i + 1)
                    }
                    if (res.data.words_result.号牌号码) {
                      this.basicForm.cph = res.data.words_result.号牌号码.words
                    }
                    if (res.data.words_result.发动机号码) {
                      this.basicForm.fdjh = res.data.words_result.发动机号码.words
                    }
                    if (res.data.words_result.注册日期) {
                      var a = res.data.words_result.注册日期.words
                      var b = parseInt(a / 10000)
                      var c = parseInt((a - b * 10000) / 100)
                      var d = a - b * 10000 - c * 100
                      var e = b + ' ' + c + ' ' + d
                      this.basicForm.djrq = new Date(Date.parse(e))
                      this.djdate()
                    }
                    if (res.data.words_result.所有人.words) {
                      this.formData[1].name = res.data.words_result.所有人.words
                    }
                    if (res.data.words_result.住址.words) {
                      this.formData[1].address = res.data.words_result.住址.words
                    }
                    loading.close();
                  })
              } else {
                this.$message.error('图片上传失败！')
                loading.close();
              }
            })
        }, 2000);
      });
    },
    beforeAvatarUpload2(file) {
      this.checkAndHandleCompression(file).then(fileOptions => {
        let {uploadSrc, uploadFile} = fileOptions;
        // 压缩完成使用 uploadSrc, uploadFile
        const params = new FormData();
        params.append('file', uploadFile)
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        setTimeout(() => {
          axios.post("/api/xszsb/xszUpload", params)
            .then((res) => {
              if (res) {
                let params = new URLSearchParams()
                params.append('url', res.data.data)
                params.append('vehicle_license_side', 'back')
                params.append('detect_direction', true)
                axios.post("https://aip.baidubce.com/rest/2.0/ocr/v1/vehicle_license?access_token=" + this.accessToken, params)
                  .then((res) => {
                    var str = res.data.words_result.核定载人数.words
                    if (str.charAt(str.length - 1) == '人') {
                      str = str.slice(0, str.length - 1)
                      this.basicForm.zkrs = Number(str)
                    } else {
                      this.basicForm.zkrs = Number(str)
                    }
                    if (res.data.words_result.号牌号码.words) {
                      this.basicForm.cph = res.data.words_result.号牌号码.words
                    }
                    loading.close();
                    loading.close();
                  })
              } else {
                this.$message.error('图片上传失败！')
                loading.close();
              }
            })
        }, 2000);
      })
    },
    beforeAvatarUpload3(file) {
      this.checkAndHandleCompression(file).then(fileOptions => {
        let {uploadSrc, uploadFile} = fileOptions;
        // 压缩完成使用 uploadSrc, uploadFile
        const params = new FormData();
        params.append('file', uploadFile)

        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        setTimeout(() => {
          axios.post("/api/xszsb/djzUpload", params)
            .then((res) => {
              if (res) {
                let params = new URLSearchParams()
                params.append('url', res.data.data)
                params.append('access_token', this.accessToken)
                axios.post("https://aip.baidubce.com/rest/2.0/ocr/v1/vehicle_registration_certificate", params)
                  .then((res) => {
                    if (res.data.words_result.date_of_production) {
                      this.basicForm.ccrq = res.data.words_result.date_of_production.words
                    }
                    if (res.data.words_result.vehicle_model) {
                      this.basicForm.ggxh = res.data.words_result.vehicle_model.words
                    }
                    if (res.data.words_result.vehicle_type) {
                      this.basicForm.lx = res.data.words_result.vehicle_type.words
                    }
                    if (res.data.words_result.registration_num) {
                      this.basicForm.cph = res.data.words_result.registration_num.words
                    }
                    if (res.data.words_result.engine_num) {
                      this.basicForm.fdjh = res.data.words_result.engine_num.words
                    }
                    if (res.data.words_result.body_color) {
                      this.basicForm.csys = res.data.words_result.body_color.words
                    }
                    if (res.data.words_result.registration_date) {
                      this.basicForm.djrq = res.data.words_result.registration_date.words
                    }
                    if (res.data.words_result.seating_capacity) {
                      this.basicForm.zkrs = res.data.words_result.seating_capacity.words
                    }
                    if (res.data.words_result.nature_of_use) {
                      this.basicForm.syxz = res.data.words_result.nature_of_use.words
                    }
                    if (res.data.words_result.vin) {
                      this.basicForm.sbdm = res.data.words_result.vin.words
                    }

                    loading.close();
                    loading.close();
                  })
              } else {
                this.$message.error('图片上传失败！')
                loading.close();
              }
            })
        }, 2000);
      });
    },
    handleProgress(event, file, fileList) {

    },
    handleChange1(file) {
      this.upload_btn1 = true
    },
    handleSuccess1(file) {
      this.upload_btn1 = true

    },

    handleChange2(file) {
      this.upload_btn2 = true
    },
    handleSuccess2(file) {
      this.upload_btn2 = true
    },

    handleChange3(file) {
      this.upload_btn3 = true
    },
    handleSuccess3(file) {
      this.upload_btn3 = true
    },

    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    checkAndHandleCompression(file) {

      return new Promise((resolve, reject) => {

        this.imgBase64(file, (image, canvas) => {
          let maxSize = 3 * 1024; // 3M (单位KB)
          let fileSize = file.size / 1024; // 图片大小 (单位KB)

          let uploadSrc, uploadFile;
          if (fileSize > maxSize) { // 如果图片大小大于maxSize，进行压缩
            uploadSrc = canvas.toDataURL(file.type, maxSize / fileSize);
            uploadFile = this.convertBase64UrlToFile(uploadSrc, file.name); // 转成file文件
          } else {
            uploadSrc = image.src;
            uploadFile = file;
          }

          let compressedSize = uploadFile.size / 1024;// 压缩后图片大小 (单位KB)
          // 判断图片大小是否小于maxSize，如果大于则继续压缩至小于为止
          if (compressedSize.toFixed(2) > maxSize) {
            this.checkAndHandleUpload(uploadFile);
          } else {
            let fileOptions = {uploadSrc, uploadFile};
            resolve(fileOptions);
          }
        });

      });

    },

    /**
     * 将图片转化为base64
     */
    imgBase64(file, callback) {
      // 看支持不支持FileReader
      if (!file || !window.FileReader) return;
      // 创建一个 Image 对象
      let image = new Image();
      // 绑定 load 事件处理器，加载完成后执行
      image.onload = function () {
        // 创建 canvas DOM 对象
        let canvas = document.createElement('canvas');
        // 返回一个用于在画布上绘图的环境, '2d' 指定了您想要在画布上绘制的类型
        let ctx = canvas.getContext('2d');
        // 如果高度超标 // 参数，最大高度
        let MAX_HEIGHT = 3000;
        if (image.height > MAX_HEIGHT) {
          // 宽度等比例缩放 *=
          image.width *= MAX_HEIGHT / image.height;
          image.height = MAX_HEIGHT;
        }
        // 获取 canvas的 2d 环境对象,
        // 可以理解Context是管理员，canvas是房子
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        // 重置canvas宽高
        canvas.width = image.width;
        canvas.height = image.height;
        // 将图像绘制到canvas上
        ctx.drawImage(image, 0, 0, image.width, image.height);

        callback(image, canvas);

      };
      if (/^image/.test(file.type)) {
        // 创建一个reader
        let reader = new FileReader();
        // 将图片将转成 base64 格式
        reader.readAsDataURL(file);
        // 读取成功后的回调
        reader.onload = function () {
          // 设置src属性，浏览器会自动加载。
          // 记住必须先绑定事件，才能设置src属性，否则会出同步问题。
          image.src = this.result;
        };
      }
    },

    /**
     * 把Base64转换成file文件
     */
    convertBase64UrlToFile(dataurl, filename) {
      let arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, {type: mime});
    },

    /**
     * 修改车辆信息表单
     */
    editClxxLabel() {
      this.isShowEditClxxLabel = true;
      for (let i = 0; i < this.clxxLabel.length; i++) {
        this.elTagInputVisible.push(false)
        this.elTagInput.push('')
        this.elTagInputRefs.push("elTagRefs" + i);
      }
    },

    /**
     * 关闭ClxxLabel
     */
    closeDrawer() {
      this.isShowEditClxxLabel = false;
      this.getLabel()
    },

    /**
     * 保存clxxLabel
     */
    saveClxxLabel() {
      let loadingInstance = this.$loading()
      updateLabel(this.clxxLabel).then((res) => {
        loadingInstance.close()
        this.$message.success('保存成功！')
        this.closeDrawer()
        this.getLabel()
      })
    },

    /**
     * 删除clxxLabel
     */
    deleteClxxLabel(index) {
      deleteLabel(this.clxxLabel[index].id)
      this.getLabel()
    },

    /**
     * 添加
     */
    addClxxLabel() {
      this.clxxLabel.push(
        {
          ywid: this.ywid,
          labelName: "labelName",
          dbName:"dbName",
          wordName:"{{dbName}}",
          type:"文本",
          priority:this.clxxLabel[this.clxxLabel.length-1].priority + 1,
          data:"",
          values:[],
          defaults:false
        }
      )
    },

    /**
     * 字段名发生变化
     */
    zdmInput(index){
      this.clxxLabel[index].wordName = "{{" + this.clxxLabel[index].dbName + "}}"
    },

    /**
     * 动态标签
     */
    handleClose(tag, index) {
      this.clxxLabel[index].values.splice(this.clxxLabel[index].values.indexOf(tag), 1);
    },

    showEgInput(index) {

      this.elTagInputVisible[index] = true;
      this.isShowEditClxxLabel = false;
      this.isShowEditClxxLabel = true;

      // this.$nextTick(_ => {
      //   this.$refs.elTagRefs+index.$refs.input.focus();
      // });
    },

    handleInputConfirm(index) {

      let elTagInput = this.elTagInput[index];
      if (elTagInput) {
        this.clxxLabel[index].values.push(elTagInput);
      }
      this.elTagInputVisible[index] = false;
      this.elTagInput[index] = '';
    }
  },
  mounted() {
    this.ywtype()
    getAccessToken().then((res) => {
      if (res) {
        this.accessToken = res.data
      }
    })
    // this.gettest()
  },
  activated() {
    this.gettest()
    this.getLabel()
  }
}
</script>

<style scoped lang="less">
.form {
  margin-top: 10px;
  margin-left: 10px;
  padding: 15px 80px 15px 15px;
  background-color: #ffffff;
  border-radius: 5px;
}

.lastform {
  margin-top: 10px;
  margin-left: 10px;
  padding: 15px 80px 15px 15px;
  background-color: #ffffff;
  border-top-left-radius: 5px;
}

.el-form-item {
  margin: 10px 20px 10px 0px;
}

.el-date-editor {
  width: 100% !important;
}

.but {
  text-align: right;
  background-color: #fff;
  margin-left: 10px;
  padding-right: 40px;
}

/deep/ input::-webkit-outer-spin-button,
/deep/ input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}

/deep/ input[type='number'] {
  -moz-appearance: textfield;
}

.el-dropdown-link {
  background-color: #2eb3ff;
  color: #fff;
  padding: 3px 8px;
  font-size: 12px;
  border-radius: 3px;
}

:deep .el-form-item__label {
  position: relative;
  display: inline-block;
  text-align-last: justify;
}

.demo-ruleForm :deep .el-form-item--medium .el-form-item__label::before {
  display: none;
}

:deep .el-dialog__header {
  display: none;
}

.hide_box1 /deep/ .el-upload--picture-card {
  display: none;
}

.hide_box2 /deep/ .el-upload--picture-card {
  display: none;
}

.hide_box3 /deep/ .el-upload--picture-card {
  display: none;
}

:deep .el-input.is-disabled .el-input__inner {
  color: #606266;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
